package com.zeno.web.core.exception;

import com.zeno.soil.util.JsonMapper;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 
 * @auth zeno
 * @date 2022/7/25 16:11
 */
public class WafExceptionResolveHandler implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException( HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex ) {

        WafExceptionResponseVO responseVO;
        if (ex instanceof WafException){
            WafException wafException = (WafException)ex;
            responseVO = WafExceptionResponseVO.createFrom(wafException);
            response.setStatus(wafException.status().value());
        }else {
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            responseVO = WafExceptionResponseVO.createFrom(ex);
        }

        try {
            ServletOutputStream os = response.getOutputStream();
            os.write(JsonMapper.toJsonString(responseVO).getBytes());
            os.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return new ModelAndView();
    }
}
